const lsSetItem = (key, value) => {
  // 将数组、对象类型的数据转化为 JSON 字符串进行存储
  if (typeof value === 'object') {
    value = JSON.stringify(value)
  }
  window.localStorage.setItem(key, value)
}

const lsGetItem = key => {
  const data = window.localStorage.getItem(key)
  try {
    return JSON.parse(data)
  } catch (err) {
    return data
  }
}

async function localSet(key, value) {
  try {
    if (!chrome?.storage) {
      lsSetItem(key, value)
      return
    }
    await chrome.storage.local.set({ [key]: value })
  } catch (error) {
    console.info(`set storage data [${key}] failed \n`, error)
  }
}

async function localMultiSet(obj) {
  try {
    if (!chrome?.storage) {
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          const element = obj[key]
          lsSetItem(key, element)
        }
      }
      return
    }
    await chrome.storage.local.set(obj)
  } catch (error) {
    console.info(`set storage data failed \n`, error)
  }
}

async function localGet(key) {
  try {
    let result
    if (!chrome?.storage) {
      result = { [key]: lsGetItem(key) }
    } else {
      result = await chrome.storage.local.get(key)
    }
    return result[key]
  } catch (error) {
    console.info(`get storage data [${key}] failed \n`, error)
    return null
  }
}

export { localGet, localSet, localMultiSet }
